package cn.yuhao.party.outtui.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.itcast.jdbc.TxQueryRunner;
import cn.yuhao.party.outtui.domain.Out;
import cn.yuhao.party.pager.PageBean;
import cn.yuhao.party.pager.PageConstants;

public class OutDao {
private QueryRunner qr = new TxQueryRunner();

	
	public PageBean<Out> findAll(int pc) {
		int ps = PageConstants.BOOK_PAGE_SIZE;// 每页记录数
		String sql = "select * from ubtuijian limit ?,?";
		try {
			String sql1 = "select count(*) from ubtuijian";
			Number number = (Number) qr.query(sql1, new ScalarHandler());
			int tr = number.intValue();// 得到了总记录数
			List<Out> listOut = qr.query(sql,
					new BeanListHandler<Out>(Out.class), (pc - 1) * ps,
					ps);
			PageBean<Out> pb = new PageBean<Out>();
			/*
			 * 其中PageBean没有url，这个任务由Servlet完成
			 */
			pb.setBeanList(listOut);
			pb.setPc(pc);
			pb.setPs(ps);
			pb.setTr(tr);

			return pb;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public Out findById(String Gtheme) {
		String sql = "select * from ubtuijian where theme=?";

		try {
			Out Out = (Out) qr.query(sql, new BeanHandler<Out>(
					Out.class), Gtheme);
			return Out;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void addOut(Out Out) {
		String sql = "insert into ubtuijian values(?,?,?,?,?)";
		Object[] params = { Out.getTheme(),Out.getTime(),Out.getContex(),Out.getLink(),Out.getPicture()};
		try {
			qr.update(sql, params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void delete(String theme) {
		String sql = "delete from ubtuijian where theme=?";
		try {
			qr.update(sql, theme);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void editOut(Out Out) {
		String sql = "update ubtuijian set time=?,contex=?,link=?,picture=?  where theme=?";
		Object[] params = { Out.getTime(),Out.getContex(),Out.getLink(),Out.getPicture(),Out.getTheme()};
		try {
			qr.update(sql, params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}
